package com.softWang.common.utils;


import com.softWang.common.base.LoginUser;
import com.softWang.common.exception.LogicException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;

import javax.servlet.http.HttpServletRequest;

/**
 * 安全服务工具类
 * 
 * @author ruoyi
 */
public class SecurityUtils
{
    /**
     * 用户ID
     **/
    public static Long getUserId()
    {
        try
        {
            return getLoginUser().getUserId();
        }
        catch (Exception e)
        {
            throw new LogicException("获取用户ID异常");
        }
    }

    /**
     * 获取当前登录的用户
     *
     * @return 用户信息
     */
    public static LoginUser getLoginUser(){
        SecurityContext context = SecurityContextHolder.getContext();
        if (context == null) {
            return null;
        }
        Authentication authentication = context.getAuthentication();
        if (authentication == null) {
            return null;
        }
        return authentication.getPrincipal() instanceof LoginUser ? (LoginUser) authentication.getPrincipal() : null;
    }

    public static void setLoginUser(LoginUser loginUser, HttpServletRequest request){
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
    }


    /**
     * 当前登录的用户是否为超管
     *
     * @return 结果
     */
    public static boolean isSysAdmin()
    {
        LoginUser user = getLoginUser();
        if(user!= null && user.getType() == 1){
            return true;
        }else {
            return false;
        }
    }
    /**
     * 当前登录的用户是否为租户管理员
     *
     * @return 结果
     */
    public static boolean isTenantAdmin()
    {
        LoginUser user = getLoginUser();
        if(user!= null && user.getType() == 3){
            return true;
        }else {
            return false;
        }
    }

    /**
     * 当前登录的是否系统租户
     *
     * @return 结果
     */
    public static boolean isSystemTenant(){
        LoginUser user = getLoginUser();
        if(user!= null && user.getTenantId() == 1){
            return true;
        }else {
            return false;
        }
    }


}
